require 'optparse'
require 'station'
require 'query'
require 'plugin'

include PCLink 

# configure default options
options = {
  :port => 9000,
  :timeout => 5
}

OptionParser.new do |opts|
  opts.banner = "Usage: main.rb [options] action [arguments]"

  opts.on("-h HOST", "--host HOST", "Server host") do |v|
    options[:host] = v
  end

  opts.on("-t N", "--timeout N", Integer, "Timeout (s) waiting for servers to connect") do |v|
    options[:timeout] = v.to_i
  end

  opts.on("-p N", "--port N", Integer, "Listener port") do |v|
    options[:timeout] = v.to_i
  end

  opts.on("-q", "--query QUERY", "Query Streamiuum server") do |v|
    options[:query] = v
  end
end.parse!

puts "Streamium (c) cjodea 2007"
action_name = ARGV.shift
exit 1 if action_name == nil

begin 
  plugin = Plugin.new(action_name)
  action = plugin.load
rescue LoadError
  puts "no such action: #{action_name}"
  exit 1
end 

station = StreamiumStation.new(options)
station.find_stations unless options[:host]
exit 1 if station.servers.length == 0 
station.connect
action.execute(station, ARGV) if action 
